package kr.ac.kaist.savehearts.status;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import kr.ac.kaist.savehearts.SaveHeartsConstants;
import kr.ac.kaist.savehearts.status.StatusUpdateListener.RequestType;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

/**
 * RequestJoinTask is AsyncTask which sends a join request to the server.
 * For successful transaction, correct information needs to be transmitted:
 * 	User's last/first name, e-mail address, phone number
 * Result of the transaction can be retrieved through StatusUpdateListener.
 * All parameters must be passed by the constructor because it does not provide
 * any get/set functions to change them.
 * RequestJoinTask also requires android.content.Context object to create
 * a progress dialog (spinner) which is shown in the middle of transaction.
 * @author Seungwook Han
 */
public class RequestJoinTask extends AsyncTask<String, Void, Integer> {

	/**
	 * Required information to join the service: firstname, lastname, e-mail, password, and phone number
	 */
	private String firstName, lastName, email, passwd, phone;
	
	/**
	 * android.content.Context object to create progress dialog
	 */
	private Context context;
	
	/**
	 * Progress dialog which will show up while waiting for a response from the server
	 */
	private ProgressDialog dialog;
	
	/**
	 * StatusUpdateListener to process a response for the request
	 * @see kr.ac.kaist.savehearts.status.StatusUpdateListener.joinFinished()
	 */
	private StatusUpdateListener listener;
	private final String URL = SaveHeartsConstants.SERVER_URL + SaveHeartsConstants.URL_JOIN;
	
	public RequestJoinTask(String firstName, String lastName, String email, 
			String passwd, String phone, Context context, StatusUpdateListener listener) {
		this.firstName = firstName;	this.lastName = lastName;
		this.email = email;	this.passwd = passwd;
		this.phone = phone;	this.context = context;
		this.listener = listener;
	}
	
	@Override
	protected void onPostExecute(Integer result) {
		if ( this.dialog != null ) this.dialog.dismiss();
		if ( this.listener != null ) 
			this.listener.responseReceived(RequestType.Join, result);
	}

	@Override
	protected void onPreExecute() {
		this.dialog = new ProgressDialog(this.context);
		this.dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		this.dialog.setMessage("Please wait...");
		this.dialog.show();
	}

	@Override
	protected Integer doInBackground(String... arg0) {
		// Create a new HttpClient and Post Header
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(this.URL);
		int ret = SaveHeartsConstants.STATUS_OK;
		
		try {
			// Send required information to join the service
			// 		Lastname, firstname, e-mail, password, phone number
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
			nameValuePairs.add(
					new BasicNameValuePair(SaveHeartsConstants.PROP_FIRSTNAME, firstName));
			nameValuePairs.add(
					new BasicNameValuePair(SaveHeartsConstants.PROP_LASTNAME, lastName));
			nameValuePairs.add(
					new BasicNameValuePair(SaveHeartsConstants.PROP_EMAIL, email));
			nameValuePairs.add(
					new BasicNameValuePair(SaveHeartsConstants.PROP_PASSWORD, passwd));
			nameValuePairs.add(
					new BasicNameValuePair(SaveHeartsConstants.PROP_PHONENUMBER, phone));
			
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			
			// Execute HTTP Post Request
			HttpResponse response = httpClient.execute(httpPost);
			String respStr = response.getEntity().toString();
			
			// do something with response....
			System.out.println(respStr);
			ret = Integer.parseInt(respStr);
			
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			ret = SaveHeartsConstants.STATUS_FAIL_UNKNOWN;
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			ret = SaveHeartsConstants.STATUS_FAIL_UNKNOWN;
		} catch (IOException e) {
			e.printStackTrace();
			ret = SaveHeartsConstants.STATUS_FAIL_UNKNOWN;
		}
		return ret;
	}
}